<?php
namespace Admin\Model;
use Think\Model;
class CategoryModel extends Model 
{
	protected $insertFields = array('cate_name','parent_id','is_floor');
	protected $updateFields = array('id','cate_name','parent_id','is_floor');
	protected $_validate = array(
		array('cate_name', 'require', '商品名称不能为空！', 1, 'regex', 3),
		array('cate_name', '1,30', '商品名称的值最长不能超过 30 个字符！', 1, 'length', 3),
		array('praent_id', 'number', '上级分类的ID，0：顶级分类必须是一个整数！', 2, 'regex', 3),
	);
    //找一个分类所有子类的ID
    public function getChildren($cateId){
        $data = $this->select();
        return $this->_getChildren($data,$cateId,TRUE);
    }
    private function _getChildren($data,$cateId,$isClear = FALSE){
        static $_ret = array();
        if($isClear){
            $_ret = array();
        foreach ($data as $k => $v){
            if($v['parent_id'] == $cateId){
                $_ret[] = $v['id'];
                $this->_getChildren($data,$v['id']);
            }
            }
            return $_ret;
        }

    }
    //获取树形结构
    public function getTree(){
        $data = $this->select();
        return $this->_getTree($data);
    }
    private function _getTree($data,$parent_id=0,$level=0){
       static $_ret = array();
        foreach ($data as $k => $v){
            if($v['parent_id'] == $parent_id){
                $v['level'] =$level;
                $_ret[] = $v;
                $this->_getTree($data,$v['id'],$level+1);
            }
        }
        return $_ret;
    }
	public function search($pageSize = 20)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		if($cate_name = I('get.cate_name'))
			$where['cate_name'] = array('like', "%$cate_name%");
		if($praent_id = I('get.praent_id'))
			$where['praent_id'] = array('eq', $praent_id);
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->alias('a')->where($where)->group('a.id')->limit($page->firstRow.','.$page->listRows)->select();
		return $data;
	}

	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
	}
	// 删除前
	protected function _before_delete($option)
	{
        $children = $this->getChildren($option['where']['id']);
		if($children)
		{
            $children =implode(',',$children);
            $model = new \Think\Model;
            $model->table("__CATEGORY__")->delete($children);
		}
	}
	/************************************ 其他方法 ********************************************/
	//获取导航条数据
    public function getNavData(){
        $catData = S('catData');
        if(!$catData){
            $all = $this->select();
            $ret =array();
            foreach ($all as $k=>$v)
            {
            if($v['parent_id'] == 0) {
            foreach ($all as $k1 => $v1)
            {
            if($v1['parent_id'] ==$v['id'])
            {
            foreach($all as $k2=>$v2)
            {
            if($v2['parent_id']==$v1['id'])
            {
                $v1['chlderen'] [] =$v2;
            }
            }
            $v['children'][] = $v1;
                 }
             }
                $ret[] = $v;
            }
        }
            //S('catData',$ret,86400);
            $ret =array_slice($ret,0,13);
            return $ret;
        }else{
            return $catData;
        }
    }
    public function parentPath($catId){
        static $ret =array();
        $info = $this->field('id,cate_name,parent_id')->find($catId);
        $ret[] = $info;
        if($info['parent_id']>0){
            $this->parentPath($info['parent_id']);
        }
        return $ret;
    }
    //获取前台首页楼层中的数据
    public function floorData(){
        $floorData =S('floorData');
        if($floorData){
            return $floorData;
        }else{
            //先取出推荐到楼层的顶级分类
            $ret = $this->where(array(
                'parent_id'=>array('eq',0),
                'is_floor' =>array('eq','是')
            ))->select();
            $goodsModel = D('Admin/Goods');
            foreach ($ret as $k=>$v){
                $goodsId = $goodsModel->getGoodsIdByCatId($v['id']);
                !$goodsId && $goodsId =array(0);
                $ret[$k]['brand'] = $goodsModel->alias('a')
                    ->join('LEFT JOIN __BRAND__ b ON a.brand_id =b.id ')
                    ->field('DISTINCT brand_id,b.brand_name,b.logo')
                    ->where(
                        array(
                            'a.id' =>array('in',$goodsId),
                            'a.brand_id'=>array('neq',0),
                        )
                    )->limit(9)->select();
                $ret[$k]['subCat'] = $this->where(array(
                    'parent_id' =>array('eq',$v['id']),
                    'is_floor' => array('eq','否'),
                ))->select();

                $ret[$k]['recSubCat'] = $this->where(array(
                    'parent_id' =>array('eq',$v['id']),
                    'is_floor' => array('eq','是'),
                ))->select();
                foreach ($ret[$k]['recSubCat'] as $k1 =>&$v1){
                    $gids = $goodsModel->getGoodsIdByCatId($v1['id']);
                    !$gids && $gids =array(0);
                    $v1['goods'] = $goodsModel->field('id,mid_logo,goods_name,shop_price')
                    ->where(array(
                        'is_on_sale'=>array('eq','Y'),
                        'is_floor' => array('eq','是'),
                        'id'        => array('in',$gids),
                     ))->order('sort_num ASC')->limit(8)->select();
                }
            }
            //S('floorData',$ret,86400);
            return $ret;
        }
    }
    //根据当前搜索出来的商品来计算筛选条件
    public function getSearchConditonByGoodsId($goodsId){
        !$goodsId && $goodsId =array(0);
        $ret =array();
        $goodsModel = D('Admin/Goods');
        //先取出这个分类下所有商品的ID
        //$goodsId=$goodsModel->getGoodsIdByCatId($catId);
        $ret['brand']=$goodsModel->alias('a')
            ->field('DISTINCT brand_id,b.brand_name,b.logo')
            ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
            ->where(array(
                'a.id'=>array('in',$goodsId),
                'a.brand_id'=>array('neq',0)
            ))->select();
        /******************  价格区间段  ****************/
        $sectionCount = 6;//默认分几段
        $priceInfo = $goodsModel->field('MAX(shop_price) max_price,MIN(shop_price) min_price')
            ->where(array(
                'id'=>array('in',$goodsId),
            ))->find();
        //最大价和最小价的区间
        $priceSection = $priceInfo['max_price'] - $priceInfo['min_price'];
        //分类下商品的数量
        $googsCount = count($goodsId);
        //只有商品数量有这些时价格才分段
        if($googsCount>1){
            //根据最大值和最小价的差值计算分几段
            if($priceSection<100)
                $sectionCount=2;
            elseif($priceSection<1000)
                $sectionCount=4;
            elseif($priceSection<10000)
                $sectionCount=6;
            else
                $sectionCount=7;
            //根据这些段数分段
            $pricePerSection =ceil($priceSection / $sectionCount);//每段的f范围
            $price=array();//存放最终的分段数据
            $firstPrice = (int)$priceInfo['min_price']; //第一个价格段的开始价格
            for($i=0;$i<$sectionCount;$i++){
                //每段结束的价格
                $_tmpEnd = $firstPrice+$pricePerSection;
                //把结束的价格取整
                $_tmpEnd = ((ceil($_tmpEnd/100))*100 - 1);
                $price[] = $firstPrice.'-' .$_tmpEnd;
                $firstPrice =$_tmpEnd+1;
            }
            $ret['price'] = $price;
        }
            //商品属性
            $gaModel =D('goods_attr');
            $gaData =$gaModel->alias('a')
                ->field('DISTINCT a.attr_id,a.attr_value,b.attr_name')
                ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id=b.id')
                ->where(array(
                    'a.goods_id'=>array('in',$goodsId),
                    'a.attr_value'=>array('neq','')
                ))->select();
            $_gaData =array();
            foreach($gaData as $k=>$v){
                $_gaData[$v['attr_name']][]=$v;
            }
            $ret['gaData'] =$_gaData;
            return $ret;
    }
}